import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart' hide Key;
import 'package:yyshort/common/apis/apis.dart';
import 'package:yyshort/common/model/index.dart';
import 'package:yyshort/common/utils/utils.dart';
import 'package:yyshort/common/widgets/widgets.dart';
import 'package:get/get.dart';

import 'index.dart';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart';

class DataEncoder {
  // 固定的拼接字符串
  static const String _fixedString = "GCV6bSE4PPHdVbZRmN8XJMXkPzfpRZVD";

  // AES加密所需的密钥和IV（实际使用中请更换为您自己的密钥）
  // AES-256需要32字节的密钥
  static const String _aesKey = "H2tQHEYz5DcsEQfAk2YubKDhV2NUxFvQ";
  // IV需要16字节
  static const String _aesIV = "daSZTpuGaMHFhR3h";

  /// 处理原始字典并生成最终的postDic
  static Map<String, String> encode(Map<String, String> originalDic) {
    // 1. 按键排序后拼接值
    List<String> sortedKeys = originalDic.keys.toList()..sort();
    String concatenatedValues = sortedKeys
        .map((key) => originalDic[key])
        .join();

    // 2. 拼接固定字符串生成新字符串
    String abc = concatenatedValues + _fixedString;

    // 3. MD5加密生成签名
    String sign = md5.convert(utf8.encode(abc)).toString();

    // 4. 在原始字典中增加签名
    Map<String, String> newDic = Map.from(originalDic);
    newDic["sign"] = sign;
    print("signDic: $newDic");

    // 5. AES256加密处理
    final key = Key.fromUtf8(_aesKey);
    final iv = IV.fromUtf8(_aesIV);
    final encrypter = Encrypter(AES(key, mode: AESMode.cbc));

    // 将字典转换为JSON字符串再加密
    final jsonString = json.encode(newDic);
    final encrypted = encrypter.encrypt(jsonString, iv: iv);

    // 6. 生成最终的postDic
    return {"receipt": encrypted.base64};
  }
}

class SignUpController extends GetxController {
  SignUpController();

  /// obs 响应式变量 才写入 state
  final state = SignUpState();

  /// 业务变量

  final TextEditingController fullnameController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passController = TextEditingController();

  /// 业务事件

  // 返回上一页
  handleNavPop() {
    Get.back();
  }

  // 提示信息
  handleTip() {
    toastInfo(msg: '这是注册界面');
  }

  // 忘记密码
  handleFogotPassword() {
    toastInfo(msg: '忘记密码');
  }

  // 执行注册操作
  handleSignUp() async {
    // if (!duCheckStringLength(fullnameController.value.text, 5)) {
    //   toastInfo(msg: '用户名不能小于5位');
    //   return;
    // }
    // if (!duIsEmail(emailController.value.text)) {
    //   toastInfo(msg: '请正确输入邮件');
    //   return;
    // }
    // if (!duCheckStringLength(passController.value.text, 6)) {
    //   toastInfo(msg: '密码不能小于6位');
    //   return;
    // }

    UserRegisterRequestEntity params = UserRegisterRequestEntity(
      email: emailController.value.text,
      password: duSHA256(passController.value.text),
    );

    await UserAPI.register(params: params);

    Get.back();
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
  }

  // 页面载入完成
  @override
  Future<void> onReady() async {
    super.onReady();
    //       // 原始请求字典
    // Map<String, String> originalDic = {
    // };

    // // 处理并生成结果
    // Map<String, String> postDic = DataEncoder.encode(originalDic);

    // // 打印结果
    // print("原始字典: $originalDic");
    // print("最终的postDic: $postDic");
    // await UserAPI.guestLogin(); // Uncomment and assign to a variable if needed, e.g.:
  }

  @override
  void dispose() {
    fullnameController.dispose();
    emailController.dispose();
    passController.dispose();
    super.dispose();
  }
}
